﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Xml;
using HWEngine.Generators;

namespace HWEngine
{
	public static class ExportExtensions
	{
		public static XmlDocument RenderToSvg(this HWGenerator hwgen, RtfText rtfText)
		{
			var svg = new XmlDocument();
			svg.AppendChild(svg.CreateXmlDeclaration("1.0", "utf-8", "no"));
			XmlElement root = svg.CreateElement("svg");
			svg.AppendChild(root);
			root.SetAttribute("version", "1.1");
			root.SetAttribute("xmlns", "http://www.w3.org/2000/svg");
			
			hwgen.BeginRender(rtfText);

			int pageNum = 0;
			while (hwgen.HasMorePages)
			{
				float yShift = pageNum * hwgen.PageBounds.Height;
				hwgen.RenderPage(w => AppendSvg(w, root, yShift));
				++pageNum;
			}
			
			root.SetAttribute("height", string.Format("{0}cm", 25 * pageNum));
			root.SetAttribute("width", "20cm");
			root.SetAttribute(
				"viewBox",
				string.Format("{0} {1} {2} {3}",
				0,
				0,
				hwgen.PageBounds.Left + hwgen.PageBounds.Width,
				(hwgen.PageBounds.Top + hwgen.PageBounds.Height) * pageNum));
			return svg;
		}

		private static void AppendSvg(Letter letter, XmlElement root, float yShift)
		{
			foreach (var line in letter.Lines)
			{
				AppendSvg(line, root, yShift);
			}
		}

		private static void AppendSvg(Line line, XmlElement root, float yShift)
		{
			XmlElement path = root.OwnerDocument.CreateElement("polyline");
			root.AppendChild(path);
			path.SetAttribute("fill", "none");
			path.SetAttribute("stroke", line.HtmlColor);
			path.SetAttribute("stroke-width", line.Width.ToString(CultureInfo.InvariantCulture));
			StringBuilder d = new StringBuilder();

			foreach (PointF point in line.CalculateSpline())
			{
				d.AppendFormat(CultureInfo.InvariantCulture, "{0},{1} ", point.X, point.Y + yShift);
			}
			path.SetAttribute("points", d.ToString());
		}
	}
}
